import sys
# 用于读取YAML和JSON格式的文件
from ansible.parsing.dataloader import DataLoader
# 用于导入资产文件
from ansible.inventory.manager import InventoryManager
# 操作单个主机信息
from ansible.inventory.host import Host
# 操作单个主机组信息
from ansible.inventory.group import Group
from uuid import uuid4
from django.core.files.storage import FileSystemStorage
from django.core.files.base import ContentFile
import configparser
fs = FileSystemStorage("/tmp/tmp_inventory")


class JsonInventory(InventoryManager):
    def __init__(self, loader, sources=None):
        super().__init__(loader, sources)
    loader = DataLoader()

    @classmethod
    def create_inventory(cls, valid_hosts:list):
        content=""
        for host in valid_hosts:
            line=host.get('ansible_ssh_host')+" "
            for k,v in host.items():
                if v:
                    line=line+k+"="+v+" "
            content=content+line+"\n"
        f = ContentFile(content)
    
        f_name = fs.save(name=str(uuid4()), content=f)
        inventory = cls(cls.loader, fs.path(f_name))
        return inventory


if __name__ == "__main__":
    try:
        inventory = JsonInventory.create_inventory("")
    except Exception as e:
        print(e)
    print(123)
